package org.icsdt.sp.service;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.icsdt.utils.IOUtils;

import android.util.Log;

public class HttpHelper {
    private static final String TAG = "HttpHelper";

    //tempo limite para a conexao
    private static int TIMEOUT;

    //caminho do servidor
    private static String URL;

    //nome do servidor
    private static String HOST;

    private static final boolean LOG_ON = true;

    public static void initTimeout(int timeout) {
	TIMEOUT = timeout;
    }

    public static void setUrl(String host, String url_path) {
	HOST = host;
	URL = "http://" + HOST + url_path;
    }

    public static String getHost() {
	return HOST;
    }

    public static String doPost(String e) throws IOException {

	if (LOG_ON) {
	    Log.d(TAG,">> " + e);
	}

	URL u = new URL(URL);
	HttpURLConnection conn = (HttpURLConnection) u.openConnection();
	conn.setRequestMethod("POST");
	conn.setDoOutput(true);
	conn.setDoInput(true);
	conn.setConnectTimeout(TIMEOUT);
	conn.connect();
	//Envia
	OutputStream out = conn.getOutputStream();
	out.write(e.getBytes("UTF-8"));
	out.flush();
	out.close();
	//Recebe
	InputStream in = conn.getInputStream();
	String s = IOUtils.toString(in);

	if (LOG_ON) {
	    Log.d(TAG,"<< " + s);
	}

	conn.disconnect();
	return s;
    }
}
